package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powernode.common.LxlException;
import com.powernode.entity.UmsResource;
import com.powernode.mapper.UmsResourceMapper;
import com.powernode.service.UmsResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author lxl
 * @since 2022-04-10
 */
@Service
public class UmsResourceServiceImpl extends ServiceImpl<UmsResourceMapper, UmsResource> implements UmsResourceService {

    @Cacheable(value = "ums", key = "'resources'")
    public List<UmsResource> getAll() {
        return getParentId(0L);
    }

    private List<UmsResource> getParentId(Long parentId){
        QueryWrapper<UmsResource> wrapper = new QueryWrapper<UmsResource>();
        wrapper.eq("parent_id",parentId);

        List<UmsResource> list = this.list(wrapper);
        for (UmsResource umsResource : list) {
            List<UmsResource> children = getParentId(umsResource.getId());
            umsResource.setChildren(children);
        }
        
        return list;
    }

    @CacheEvict(value = "ums", key = "'resources'")
    public Boolean add(String name, Integer type, Integer level , Long parentId, String frontUrl, String backUrl) {
        UmsResource umsResource = new UmsResource(
                name,
                type,
                level,
                parentId,
                frontUrl,
                backUrl
        );
        return this.save(umsResource);
    }

    public Boolean check(String fieldName, String value,Long id) {
        QueryWrapper<UmsResource> wrapper = new QueryWrapper<UmsResource>();
        wrapper.eq(fieldName,value);
        if (id != null){
            //如果进来就证明是修改，必须跟不是我的id的对象的属性不重复
            wrapper.ne("id",id);
        }
        return this.count(wrapper) == 0;
    }

    @CacheEvict(value = "ums", key = "'resources'")
    public Boolean update(Long id,String name,Integer type,Integer level,Long parentId,String frontUrl,String backUrl) {
        UmsResource umsResource = new UmsResource(
                name,
                type,
                level,
                parentId,
                frontUrl,
                backUrl
        );
        umsResource.setId(id);
        return this.updateById(umsResource);
    }

    @CacheEvict(value = "ums", key = "'resources'")
    public Boolean del(Long id) throws Exception {
        QueryWrapper<UmsResource> wrapper = new QueryWrapper<UmsResource>();
        wrapper.eq("parent_id",id);
        if (this.count(wrapper) > 0){
            throw new LxlException("存在下级数据，无法进行删除");
        }

        return this.removeById(id);
    }
}
